package com.eatme.web.util;

import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.Map;

public class WeChatUtil {
    private static final Logger LOG = LoggerFactory.getLogger(WeChatUtil.class);
    public static String getDecodeData(Map<String,String> map) {
        LOG.info("需要解密的数据:{}",map);
        return getDecodeData(map.get("encryptedData"),map.get("iv"),map.get("session_key"));
    }


    public static String getDecodeData(String encryptedData, String iv,String session_key) {
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(session_key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                return new String(resultByte, "UTF-8");
            }
        } catch (NoSuchAlgorithmException
                 | NoSuchPaddingException
                 | InvalidParameterSpecException
                 | IllegalBlockSizeException
                 |BadPaddingException
                 |UnsupportedEncodingException
                 |InvalidKeyException
                 |InvalidAlgorithmParameterException
                 |NoSuchProviderException
                e) {
            LOG.info(e.getMessage(),e);
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        // {encryptedData=
        // ,
        // iv=, session_key==}
        //{"encryptedData":
        String content ="UMhBAO7+Y+396H7Fd8J+OElfyvOuSjWxqq8c7egZowLoHCNU2iF3dvMaMDaSSc+QSgBG0Qk9y4sUYvGzk0HiaEriHtHzy71kxLiXk1UkNXqrNF+nTgjuXVDfq0ooZBvLg5yta72iC+RQrF5j/z/+vvpBUCSgx1zVeNO1iChBTvazrt33cXou59yBZa65h7zMhyRyc7fMV+paXaDveGO2RoT6d1kO5x5CJhiv0D9B4ckradwegx/7+zUyzihrmYp40viOqxtkqdTMJ66Z9bcGe4i0aAgN4p16mHkITGRwTK8jUVqwXqHu9my24MtfQ2z3H5XiEsL0LZ/sHm7O+0MQWeDXcgxhQuYrDLNQ6fdGeUfYgVGYQvjFtZTeBElhyV+VVDhT81qulNPO6DP/TrjNd1GkKljLLg5BeGokWSrc6w0DLbBKesxL5VzLPp2+T5Xr";
        String iv = "UMhBAO7+Y+396H7Fd8J+OElfyvOuSjWxqq8c7egZowLoHCNU2iF3dvMaMDaSSc+QSgBG0Qk9y4sUYvGzk0HiaEriHtHzy71kxLiXk1UkNXqrNF+nTgjuXVDfq0ooZBvLg5yta72iC+RQrF5j/z/+vvpBUCSgx1zVeNO1iChBTvazrt33cXou59yBZa65h7zMhyRyc7fMV+paXaDveGO2RoT6d1kO5x5CJhiv0D9B4ckradwegx/7+zUyzihrmYp40viOqxtkqdTMJ66Z9bcGe4i0aAgN4p16mHkITGRwTK8jUVqwXqHu9my24MtfQ2z3H5XiEsL0LZ/sHm7O+0MQWeDXcgxhQuYrDLNQ6fdGeUfYgVGYQvjFtZTeBElhyV+VVDhT81qulNPO6DP/TrjNd1GkKljLLg5BeGokWSrc6w0DLbBKesxL5VzLPp2+T5Xr";
        String key = "6bjnnQ/jnb1NM8BzR6yF9Q=";
        String result = getDecodeData(content,key,key);
        LOG.info("result: {}",result);
    }
}